package tmp;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
    static DruidDataSource ds;
    static ThreadLocal<Connection>local;
    static {
        local=new ThreadLocal<>();
        Properties p=new Properties();
        ds=new DruidDataSource();
        try {
            p.load(DBUtil.class.getClassLoader().getResourceAsStream("driver.properties"));
            System.out.println(p);
            ds.configFromPropety(p);
        } catch (IOException e) {
            System.out.println("读取配置文件失败");
        }
    }


    public static Connection getConnection(){
        Connection con=local.get();
        if(con==null){
            try{
                con=ds.getConnection();
                local.set(con);
            }catch (Exception e){
                System.out.println("获取数据库连接失败");
            }
        }
        return con;
    }

    public static void close(Connection con, Statement st, ResultSet rs){
        try {
            if (con != null&&con.getAutoCommit()) {

                con.close();
                local.remove();
            }
            if (st != null) {
                st.close();
            }
            if (rs != null) {
                rs.close();
            }
        }
        catch(Exception e){
            System.out.println("数据库关闭出错");
        }
    }
}
